package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.RecommendUserDto;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLocationApi userLocationApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    /**
     * 查询今日佳人
     *   目的：根据toUserId查询推荐的用户数据，只查询score最高的一条
     */
    public TodayBest todayBest() {
        //1、获取当前用户id：toUserId
        Long toUserId = UserHolder.getUserId();
        //2、调用API查询数据：RecommendUser    userId:推荐给我的用户id  ，toUserId:我的id
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(toUserId);
        //3、如果数据不存在，构建一个默认值
        if(recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l); //默认的推荐用户id
            recommendUser.setScore(95d);
        }
        //4、根据RecommendUser中的userId查询用户详情
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        //5、构造vo
        return TodayBest.init(userInfo, recommendUser);
    }

    //查询推荐用户分页列表
    /**
     * 返回值：PageResult，内部封装TodayBest的数据列表
     * 查询的数据库表：recomment_user
     * 查询的参数：toUserId(当前的用户id)
     */
//    public PageResult recommendation(RecommendUserDto dto) {
//        //1、获取当前用户id：toUserId
//        Long toUserId = UserHolder.getUserId();
//        //2、调用API分页查询  ：toUserId,page，pagesize
//        List<RecommendUser> list = recommendUserApi.queryRecommendUserList(toUserId,dto.getPage(),dto.getPagesize());
//        //3、调用API的返回值  ：分页的数据列表： List<recommentuser>
//        if(list == null && list.size()<0) {
//            list = defaultList();
//        }
//        //4、recommentuser 只有 userId,toUserId,score
//        //5、循环数据列表，一个recommentuser转换一个TodayBest
//        List<TodayBest> vos = new ArrayList<>();
//        for (RecommendUser user : list) {
//            //6、需要根据recommentuser的userId查询userInfo
//            UserInfo userInfo = userInfoApi.findById(user.getUserId());
//            TodayBest vo = TodayBest.init(userInfo, user);
//            vos.add(vo);
//        }
//        //7、构建返回值
//        return new PageResult(dto.getPage(),dto.getPagesize(),0l,vos);
//    }

    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取当前用户id：toUserId
        Long toUserId = UserHolder.getUserId();
        //2、调用API分页查询  ：toUserId,page，pagesize
        List<RecommendUser> list = recommendUserApi.queryRecommendUserList(toUserId,
                dto.getPage(),dto.getPagesize());
        //3、调用API的返回值  ：分页的数据列表： List<recommentuser>
        if(list == null || list.size()<=0) {
            list = defaultList();
        }
        //4、提取所有list集合对象中的userId
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);//list集合，对象的属性名，属性的类型
        //5、调用UserInfoAPI根据id集合查询用户详情列表
        Map<Long,UserInfo> map = userInfoApi.findByIds(userIds);
        //6、一个RecommendUser构造一个TodayBest
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser recommendUser : list) {
            Long userId = recommendUser.getUserId(); //userId的用户详情在list1的那个位置？
            UserInfo userInfo = map.get(userId);
            TodayBest vo = TodayBest.init(userInfo, recommendUser);
            vos.add(vo);
        }
        //7、构建返回值
        return new PageResult(dto.getPage(),dto.getPagesize(),0l,vos);
    }

    public List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        for (int i=0;i<10;i++) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i + 1l); //默认的推荐用户id
            recommendUser.setScore(95d);
            list.add(recommendUser);
        }
        return list;
    }

    /**
     * 查看佳人信息
     */
    public TodayBest personalInfo(Long userId) {
        Long toUserId = UserHolder.getUserId();
        //1、查询对方的用户详情
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、查询两者的推荐信息
        RecommendUser recommendUser = recommendUserApi.queryByUserId(userId,toUserId);

        //保存，访问记录
        Visitors visitors = new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(UserHolder.getUserId());
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        visitors.setFrom("首页");
        //需要调用API查询
        visitors.setScore(recommendUser.getScore());
        visitorsApi.save(visitors);

        //3、构造vo
        return TodayBest.init(userInfo,recommendUser);
    }

    //查询指定用户的陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢java吗？" :question.getTxt();
    }

    /**
     * 回复陌生人问题
     *   ：调用环信的工具，向目标用户发送一条消息
     */
    public void replay(Long friendId, String replay) {
        Long userId = UserHolder.getUserId();
        Map map = new HashMap();
        map.put("userId",userId);
        map.put("huanXinId","hx"+userId);
        UserInfo info = userInfoApi.findById(userId);
        map.put("nickname",info.getNickname());
        String questions = strangerQuestions(friendId);
        map.put("strangerQuestion",questions);
        map.put("reply",replay);
        //转化json
        String message = JSON.toJSONString(map);
        //发送消息
        huanXinTemplate.sendMsg("hx"+friendId,message);
    }

    //搜附近
    public List<NearUserVo> search(String gender, String distance) {
        //1、获取用户的id
        Long userId = UserHolder.getUserId();
        //2、调用API查询当前用户附近的用户id集合  List<Long>
        List<Long> userIds = userLocationApi.findNear(userId,Long.valueOf(distance));  //将所有的附近人查询
        //3、查询附近所有的人的用户信息 List<UserInfo>
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //4、一个UserInfo构造一个VO对象
        List<NearUserVo> vos = new ArrayList<>();
        //循环所有的用户id
        for (Long id : userIds) {
            //排除自己
            if(id == userId) {
                continue; //跳过本次循环
//                break;   结束所有循环
            }
            UserInfo userInfo = map.get(id);
            //筛选性别
            if(!StringUtils.isEmpty(gender)) {
                if(!gender.equals(userInfo.getGender())) {
                    continue; //跳过本次循环
                }
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            vos.add(vo);
        }
        return vos;
    }
}
